<!DOCTYPE html>
<html>
<title><{$title}></title>
<head>
  <meta charset="UTF-8">
  <style>
    .el-dialog__body {
        padding: 0 10px 40px 10px  !important;
    }
    .el-table .warning-row {
      background: red;
      color: #fff;
    }
    .list > div {border:1px solid #606266;margin-top:-1px;padding-left: 10px;text-align: left;min-height: 30px;line-height: 30px;font-size: 15px;color:#606266;font-family: Helvetica;}
    .middle{display: inline-block;height: 250px;line-height: 250px;text-align: center;width: 5%;}
    .half {display: inline-block;width: 30%;padding: 0;margin: 0;vertical-align: top;}
    .right{float: right;}
  </style>
  <!-- import CSS -->
  <{webcontrol type='LoadJsCss' src="Resource/Script/layui/layui/css/layui.css"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/layui/style/admin.css"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/index.css"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/vue.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/index.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/axios.min.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/components.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/components_card.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/components_table.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/components_popup_select.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/vue/element/components_image_phone_pull.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/jquery.1.9.1.js"}>
  <{webcontrol type='LoadJsCss' src="Resource/Script/Sortable.js"}>
</head>
<body>
  <div class="" id="div1">
    <el-container>
        <el-main>
          <el-form
            :model="row"
            ref='ruleForm'
            :rules="rules"
            @submit.native.prevent
            >
            <comp-card
              card-width-col="8"
              card-height="100%"
              :card-title="formTitle"
              >
              <template slot="body">
                <el-form-item
                  v-for="item,i in formItems"
                  :key="item.name"
                  :label="item.title"
                  :prop="item.name"
                  label-width="100px"
                  >
                  <component
                    :is="item.type"
                    :fld="item"
                    :value="row[item.name]"
                    @input="row[item.name]=arguments[0]"
                    :ref="item.name"
                    @changeimg="changeFile"
                    >
                    <!-- 以下插件对多选控件有效,用来显示多选结果,如果不定义,则显示多选控件的默认效果popover效果 -->
                    <!--
                    <template slot="selectionSlot">
                      <span>bbbbb</span>
                    </template>
                    -->
                  </component>
                </el-form-item>
              </template>

            </comp-card>
          </el-form>
        </el-main>
      </el-container>
      <!-- 弹框 -->
      <el-dialog title="数据表格 - [字段处理]" :show-close="false" :visible.sync="dialogFieldVisible" width="90%" top="30px" destroy-on-close>
        <template slot-scope="scope">
          <div class="list-complete-item list half" id="list1" >
            <el-row v-for="(son ,key) in proInfo" :key="key" class="drag-handle dargDiv">
              {{son}}:{{key}}
              <el-button class="right" size="mini" @click="removeProInfo(key)">删除</el-button>
            </el-row>
          </div>

          <span class=" middle">=></span>
          <div class="list half" id="list2">
            <el-row v-for="(son ,index) in readData" :key="son.index" class="drag-handle dargDiv">
              第{{index+1}}列 => {{son.text}}
            </el-row>
          </div>

          <div class="half">
            <el-row v-for="(son ,key) in contrastData" :key="key" class="drag-handle dargDiv">
              field :{{son.field}} => data :{{son.data}}
            </el-row>
          </div>

        </template>
         <template slot="footer">
          <el-button type="primary" @click="submitForm('ruleForm')" :disabled="disableSubmit"><{$form.submit.text|default:'提交'}></el-button>
        </template>
      </el-dialog>

      <el-dialog title="数据表格 - [数据处理]" :show-close="false" :visible.sync="dialogTableVisible" width="90%" top="30px" :before-close="beforeClose">
        <el-table :data="gridData" max-height="500px">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column v-for="(item,colKey) in importCol" :colK="colKey" :property="colKey" :label="item" width="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tag v-if="scope.column.property=='errorMsg'"
                :type="scope.row.fail ? 'danger' : 'success'"
                disable-transitions>{{scope.row.errorMsg || '数据正常'}}</el-tag>
              <span v-else>{{scope.row[scope.column.property]}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="dialog-footer" >
          <el-button @click="handleClose">不导入了</el-button>
          <el-button type="primary" :disabled="disabled" @click="confirmData">确认并提交数据</el-button>
        </div>
        <el-table :data="gridData" max-height="500px">
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column v-for="(item,colKey) in importCol" :colK="colKey" :property="colKey" :label="item" width="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-tag v-if="scope.column.property=='errorMsg'"
                :type="scope.row.fail ? 'danger' : 'success'"
                disable-transitions>{{scope.row.errorMsg || '数据正常'}}</el-tag>
              <span v-else>{{scope.row[scope.column.property]}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="dialog-footer">
          <el-button @click="handleClose">不导入了</el-button>
          <el-button type="primary" :disabled="disabled" @click="confirmData">确认并提交数据</el-button>
        </div>
      </el-dialog>
  </div>
</body>



<script>
  var title='<{$title|default:"编辑"}>';
  var row = <{$row|@json_encode}>;
  var formItems = <{$formItems|@json_encode}>;
  var rules = <{$rules|@json_encode}>;
  var importCol = <{$importCol|@json_encode}>;
  var action = "<{$action}>";
  var actionConfirm = "<{$actionConfirm}>";
  let initProInfo = <{$arrFieldInfo|@json_encode}>;
  var callbacks = [];
// sontpl加载，可以加载多个，不需要<script>
<{if $sonTpl}>
  <{if $sonTpl|@is_string==1}>
    <{include file=$sonTpl}>
  <{else}>
    <{foreach from=$sonTpl item=js_item}>
      <{include file=$js_item}>
    <{/foreach}>
  <{/if}>
<{/if}>



  var app = new Vue({
    el: '#div1',
    data: function() {
      //对验证规则进行预处理,字符串改为函数
      for (var k in rules) {
        rules[k].forEach((rule,index)=>{
          if(!rule.validator) return;
          // console.log('validator found',rule.validator);
          if(!callbacks.hasOwnProperty(rule.validator)) {
            alert(`sontpl中未对callbacks[${rule.validator}]进行定义`);
            return;
          }
          rule.validator = callbacks[rule.validator];
        });
      }

      //对数据集进行预处理,避免数据集中的值不符合组件要求
      formItems.forEach(function(item,i){
        //如果自动完成控件,数据集中必须存在对应字段,否则控件有问题
        if(!row.hasOwnProperty(item.name)) {
          if(item.type=='comp-checkbox-group' ||
            item.type=='comp-pop-multi-select' ||
            item.type=='comp-image' ||
            item.type=='comp-file'
            ) {
            row[item.name] = [];
          } else {
            row[item.name] = '';
          }
        }
      });
      return {
        //表单标题
        formTitle : title,
        //提交按钮是否禁用
        disableSubmit : false,
        dialogTableVisible : false,
        dialogFieldVisible : false,
        disabled : true,
        //表单项
        formItems:formItems,
        //数据集
        row:row,
        //表单验证
        rules:rules,
        //提交数据action
        action:action,
        actionConfirm:actionConfirm,
        importCol:importCol,
        gridData:[],
        //回调接口集合
        callbacks:callbacks,//所有表单元素的自定义事件的回调集合
        'targetUrl':<{$targetUrl|@json_encode}>||null,
        readData:[],
        proInfo:initProInfo,
        contrastData:[],
      }
    },
    methods : {
      changeFile : function(fileList,obj){
        this.dialogFieldVisible=true;
        var params = fileList[0]['response']['data'];
        if(!params) return;
        this.readData = params;
        this.$nextTick(()=>{
          // this.sortableDragdrop('#list1'); //左侧暂不能移动
          this.sortableDragdrop('#list2');
        });
        this.flushData();
      },
      removeProInfo:function(k){
        // delete this.proInfo[k];
        // this.$forceUpdate()();
        app.$delete(this.proInfo,k);
        this.flushData();
      },
      //表单提交事件
      submitForm(formName) {
        this.dialogFieldVisible=false;
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            console.log('表单验证失败!!');
            return false;
          }
          this.disableSubmit = true;
          console.log('form submit fired,params',this.row);
          this.$http.post(this.action,this.row).then((res)=>{

            setTimeout(() => {
              this.disableSubmit = false;
            }, 2000);

            var url = res.data.targetUrl;
            this.gridData = res.data.gridData || [];
            this.dialogTableVisible = true;
            // console.log('this.row',this.row);
            //滞空，服务端数据已经删除了
            this.row.filePath = [];

            if(res.data.fail == 0){
              this.disabled = false;
            }

            this.$notify.success({
              title:'成功',
              message:res.data.msg+(url ? ',2秒后返回' : ''),
            });
            // this.$message(res.data.msg,'success');
            if(url) {
              setTimeout(function(){
                window.location.href = url;
              },2000);
            }
          }).catch(function (error) {
            this.$notify.error({
              'title':'请求失败',
              'message':'请求失败,检查url或者其他设置'
            });
            // this.$message('请求失败,检查url或者其他设置','error');

            this.disableSubmit = false;
          });
        });
      },
      //表单重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      beforeClose(done){
        var that = this;
         this.$confirm('关闭后将停止上传，确认关闭吗？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      handleClose(done){
        var that = this;
         this.$confirm('关闭后将停止上传，确认关闭吗？')
          .then(_ => {
            that.dialogTableVisible =false;
          })
          .catch(_ => {});
      },
      confirmData(){
        // console.log('导入数据');
        if(!this.gridData.length){
          this.$notify.error({
            'title':'失败',
            'message':'没有读取到有效导入数据明细'
          });
          return false;
        }

        this.disabled = true;
        this.$http.post(this.actionConfirm,{rows:this.gridData}).then((res)=>{
            if(res.data.gridData.length > 0){
              this.gridData = res.data.gridData || [];
            }
            if(res.data.gridData.length == 0){
              this.dialogTableVisible = false;
            }
            if(!res.data.success) {
              this.$notify.error({
                'title':'失败',
                'message':res.data.msg ? res.data.msg : '数据导入失败'
              });
              this.disabled = false;
              console.log(res);
              return false;
            }

            var url = res.data.targetUrl ? res.data.targetUrl : this.targetUrl;

            this.$notify.success({
              title:'成功',
              message:res.data.msg+(url ? ',2秒后返回' : ''),
            });
            // this.$message(res.data.msg,'success');
            this.disabled = false;
            if(url) {
              setTimeout(function(){
                window.location.href = url;
              },2000);
            }
          }).catch(function (error) {
            this.$notify.error({
              'title':'请求失败',
              'message':'请求失败,检查url或者其他设置'
            });
            // this.$message('请求失败,检查url或者其他设置','error');

            this.disabled = false;
          });
      },
      tableRowClassName(row, rowIndex){
        if (row.row.fail > 0) {
          return 'warning-row';
        }

        return '';
      },
      clickRow(s){
        console.log(s);
      },
      sortableDragdrop: function (k) {
        let _this = this;
        Sortable.create(document.querySelector(k), {
          handle: '.drag-handle',
          animation: 150,
          onSort: function (evt) {

          },
          onEnd: function (evt) {
            // console.log(evt);
            var curData = k=='#list1'?_this.proInfo:_this.readData;
            var navIndex = Object.assign(curData);
            navIndex.splice(evt.newIndex, 0, navIndex.splice(evt.oldIndex, 1)[0]);
            _this.readData = navIndex;
            _this.$forceUpdate();
            for (let index in navIndex){
              console.log('index: ' + index + ',name: ' + curData[index].text);
            }
            _this.flushData();
          },
        });
      },
      flushData:function(){
        let _this = this;
        var curData =_this.readData;
        var proData =_this.proInfo;
        var i =0;
        var res = [];
        for (let index in proData){
          console.log('index: ' + index + ',field: ' + proData[index]+ ',data: ' + curData[i].text);
          var temp = {
            field:proData[index],
            data:curData[i].text,
          };
          res.push(temp);
          i++;
        }
        this.contrastData =res;
      },

    },
    mounted : function() {

    },
    watch:{
      readData:{ //监听的对象
        deep:true, //深度监听设置为 true
        immediate: true,
        handler:function(newV,oldV){

        }
      }
    }
  });
</script>

</html>